/*
 * @Author: zwb
 * @Date: 2019-01-15 17:05:02
 * */

<template>
  <div class="v-container">
    <v-header title="支付">
      <span class="back" @click="goBack">
        <i class="el-icon-arrow-left"></i>
      </span>
    </v-header>
    <div class="v-main">

      <div class="xc">
        <div class="g-fl">
          <span id="activityName">普通洗车（全车型）</span>
        </div>
        <div class="g-fr">
          <span class="buynum">购买数量 X 1</span>
        </div>
        <div class="g-clearfix"></div>
      </div>
      <div class="tit">订单详情</div>
      <div class="price-box">
        <p>支付金额</p>
        <p class="old-price">￥30</p>
        <p id="proPrice" class="new-price">￥{{price}}.00</p>
      </div>
      <div class="g-clearfix"></div>
      <div class="rongqi">
        <div id="0" v-on:click="select_type('1')" class="paystyle jg">
          <div class="g-fl">
            <span class="xiche"><img src="@/assets/images/WeChat_pay.png" width="35px">&nbsp;&nbsp;微信支付</span>
          </div>
          <div class="yes g-fr" :class="select_data=='1'?'dui':''"></div>
          <div class="g-clearfix"></div>
        </div>
        <!-- <p>&nbsp;</p>
          <div id="0" v-on:click="select_type('2')" class="paystyle jg">
              <div class="fl"><span class="xiche"><img src="@/assets/images/logo_yl.png" width="35px">&nbsp;&nbsp;银联支付</span></div>
              <div class="yes fr" :class="select_data=='2'?'dui':''" ></div>
              <div class="clearfix"></div>
          </div> -->
      </div>
      <p class="care">*抢购成功后请尽快到盛大网点使用，有效期30天。逾期失效，不退不换。</p>
      <p class="me">剩余名额：{{leastNumber}}</p>
      <div class="bottom-submit">
        <mt-button class="my-button round" @click="paySubmit">立即支付</mt-button>
      </div>
    </div>
    <div v-html="frontUP"></div>
  </div>

</template>


<script>
import vHeader from '@/components/Header.vue';
import { Resource } from '@/services/resource';
import { MessageBox } from 'mint-ui';
const proxy = require('@/env/proxy');
const locaHref = proxy.locaHref;
import $ from 'jquery';
// import Cookies from 'js-cookie';

export default {
  name: 'pay',
  components: {
    vHeader
  },
  data() {
    return {
      select_data: '1', // 选择支付方式
      frontUP: '',
      price:'',
      leastNumber:''
      
    };
  },
  mounted() {
    this.price=localStorage.price;
    this.leastNumber=localStorage.leastNumber;
  },
  beforeDestroy() {},
  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    // 跳转页面
    pageTo(name) {
      this.$router.push(name);
    },
    // 选择支付方式
    select_type(id) {
      this.select_data = id;
    },
    // 立即支付
    paySubmit() {
      let that = this;
      that.weixinPay(); // 公众号
      // const msgBox = MessageBox({
      //   title: '提示',
      //   message: '使用交通银行信用卡支付享5元优惠体验，其他支付方式需支付原价30元',
      //   showCancelButton: true
      // });
      // msgBox.then(action => {
      //   if (action === 'confirm') {
      //     // if (sessionStorage.type == '1') {
      //       that.weixinPay(); // 公众号
      //     // } else {
      //     //   that.formSubmitWX(); // h5支付
      //     // }
      //   }
      // });
    },
    // 微信公众号支付
    weixinPay() {
      let that=this;
      pay();
      // let prepay_id;
      let paySign;
      let appId;
      let timeStamp;
      let nonceStr;
      let packageStr;
      let signType;
      /* function GetQueryString(name) {
        let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        let r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
      } */
      function pay() {
        let curr = new Date();
        let m = curr.getMonth() + 1;
        if (m < 10) {
          m = '0' + m;
        }
        let d = curr.getDate();
        if (d < 10) {
          d = '0' + d;
        }
        let h = curr.getHours();
        if (h < 10) {
          h = '0' + h;
        }
        let mi = curr.getMinutes();
        if (mi < 10) {
          mi = '0' + mi;
        }
        let s = curr.getSeconds();
        if (s < 10) {
          s = '0' + s;
        }
        // let strDatetime = '' + curr.getFullYear() + m + d + h + mi + s;
        // let code = GetQueryString('code');
        let _payType="";
        switch(that.price){
          case "1":
            _payType="1";
              break;
          case "8":
            _payType="2";
              break;
          case "18":
            _payType="3";
              break;
        }
        Resource.payConfirm.post({}, { code:sessionStorage.code,payType:_payType,needToken:true }).then(res => {
          
          if(res.head.resultCode=="000000"){
            var _tactivityOrderDO=res.body.tactivityOrderDO;
            sessionStorage.orderId=_tactivityOrderDO.orderId;
            sessionStorage.endTime=_tactivityOrderDO.endTime;
            sessionStorage.matrixContent=_tactivityOrderDO.matrixContent;
            let data1 = res.body.resultJson;
            let pnPayStr1 = eval('(' + data1 + ')');
            if (pnPayStr1.resultCode == 'SUCCESS') {
              let pnPayStr = eval('(' + pnPayStr1.pnPayStr + ')');
              appId = pnPayStr.appId;
              paySign = pnPayStr.paySign;
              timeStamp = pnPayStr.timeStamp;
              nonceStr = pnPayStr.nonceStr;
              packageStr = pnPayStr.packageStr;
              signType = pnPayStr.signType;
              callpay();
            } else {
              // that.pageTo('fail');
              MessageBox.alert('授权失败,重新获取授权信息','温馨提示').then(action => {
                if (action === 'confirm') {
                  // clearInterval(_time);
                  window.location.href =locaHref
                }
              });
              // let _time;
              // let _timeNum = 5;
              // MessageBox.alert('授权失败,重新获取授权信息<span id="daojishi" style="color:#e44947">5</span>秒','温馨提示').then(action => {
              //   if (action === 'confirm') {
              //     clearInterval(_time);
              //     this.pageTo('mainpage');
              //   }
              // });
              // _time = setInterval(function() {
              //   _timeNum--;
              //   if (_timeNum >= 0) {
              //     $('#daojishi').text(_timeNum);
              //   } else {
              //     clearInterval(_time);
              //     this.pageTo('mainpage');
              //   }
              // }, 1000);
            }
            
          }else{
            MessageBox.alert(res.head.resultMsg,'温馨提示').then(action => {
             
            });
          }
          
        });
      }

      function callpay() {
        if (typeof WeixinJSBridge == 'undefined') {
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
          }
        } else {
          onBridgeReady();
        }
      }

      function onBridgeReady() {
        window.WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          {
            appId: appId, // 公众号名称，由商户传入
            paySign: paySign, // 微信签名
            timeStamp: timeStamp, // 时间戳，自1970年以来的秒数
            nonceStr: nonceStr, // 随机串
            package: packageStr, // 预支付交易会话标识
            signType: signType // 微信签名方式
          },
          function(res) {
            if (res.err_msg == 'get_brand_wcpay_request:ok') {
              // window.location.replace("index.html");
              // window.location.href = "http://baidu.com";
              // window.location.href = 'result.jhtm?time=' + new Date().getTime();
             that.pageTo('result');
            //  MessageBox.alert('支付成功！','温馨提示').then(action => {
            //     if (action === 'confirm') {
            //       this.pageTo('result');
            //     }
            //   });
            } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
              // that.pageTo('fail');
              // let _time;
              // let _timeNum = 5;
              MessageBox.alert('支付取消,重新获取授权信息','温馨提示').then(action => {
                if (action === 'confirm') {
                  // clearInterval(_time);
                  window.location.href =locaHref
                }
              });
              // _time = setInterval(function() {
              //   _timeNum--;
              //   if (_timeNum >= 0) {
              //     $('#daojishi').text(_timeNum);
              //   } else {
              //     clearInterval(_time);
              //     this.pageTo('fail');
              //   }
              // }, 1000);
            } else if (res.err_msg == 'get_brand_wcpay_request:fail') {
              that.pageTo('fail');
              // let _time;
              // let _timeNum = 5;
              // MessageBox.alert('支付失败,重新获取授权信息<span id="daojishi" style="color:#e44947">5</span>秒','温馨提示').then(action => {
              //   if (action === 'confirm') {
              //     clearInterval(_time);
              //     this.pageTo('fail');
              //   }
              // });
              // _time = setInterval(function() {
              //   _timeNum--;
              //   if (_timeNum >= 0) {
              //     $('#daojishi').text(_timeNum);
              //   } else {
              //     clearInterval(_time);
              //     this.pageTo('fail');
              //   }
              // }, 1000);
            } // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
          }
        );
      }
    },
    // 微信H5支付
    formSubmitWX() {
      Resource.payConfirm.post({}, { type: 2 }).then(res => {
        localStorage._source_biaoshi = 1;
        let orderId = res.orderId;
        localStorage.orderId = orderId;
        let html = JSON.parse(res.html);
        window.location.replace(html.mweb_url);
        setTimeout(function() {
          location.reload();
          const msgBox = MessageBox({
            title: '提示',
            message: '若您已支付成功，请点击支付已完成',
            confirmButtonText: '支付已完成',
            cancelButtonText: '再次支付',
            showCancelButton: true
          });
          msgBox.then(action => {
            localStorage._source_biaoshi = 0;
            if (action === 'confirm') {
              Resource.orderQuery.post({}, { orderId: localStorage.orderId }).then(res => {
                let status = res.status;
                if (status != 0) {
                  this.$router.push('order');
                } else {
                  MessageBox.alert('订单未支付，请重新付款<br>若您确定已支付成功，请联系客服','温馨提示');
                }
              });
            }
          });
        }, 1000);
      });
    }
  }
};
</script>

<style lang="less" scoped>
@import url('./pay.less');
</style>
